package com.example.testapp.activity.activity.menu;

import android.app.TimePickerDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TimePicker;
import android.widget.Toast;

import com.example.testapp.R;
import com.example.testapp.activity.dabastate.CalendarDao;
import com.example.testapp.activity.model.CalendarTag;
import com.example.testapp.activity.model.CalendarVO;
import com.example.testapp.activity.util.CalendarContract;
import com.example.testapp.activity.util.LunarCalendar;
import com.example.testapp.activity.view.BorderTextView;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

/**
 * Created by l on 2016/6/5.
 */
public class CalendarViewActivity extends AppCompatActivity {

    private BorderTextView  mCalendarTop = null;
    private BorderTextView  mCalendarType = null;
    private BorderTextView  mCalendarDate = null;
    private BorderTextView  mCalendarSave = null;
    private EditText  mCalendarEdit = null;

    private LunarCalendar lc = null;
    private CalendarDao  Dao = null;
    private ArrayList<CalendarTag> dateTagList = new ArrayList<CalendarTag>();
    private static ArrayList<String> CalendarDate = null;

    private static int hour = -1;
    private static int minture = -1;

    private String calendarYear = " ";
    private String calendarMonth = " ";
    private String calendarDay = " ";
    private String week = " ";

    private String tempMonth = " ";
    private String tempDay = " ";

    private String[] sch_type = CalendarContract.sch_type;
    private String[] remind = CalendarContract.remind;
    private int sch_typeId = 0; //日程类型
    private int remindID = 0; //提醒类型

    private static String schText = "";
    private int schTypeID = 0;

    public CalendarViewActivity(){
        lc = new LunarCalendar();
        Dao = new CalendarDao(this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_calendar_view);

        initView();
    }

    private void initView() {
        mCalendarTop = (BorderTextView)findViewById(R.id.calendarTVTop);
        mCalendarDate = (BorderTextView)findViewById(R.id.calendarTVDate);
        mCalendarSave = (BorderTextView)findViewById(R.id.calendarTVSave);
        mCalendarType = (BorderTextView)findViewById(R.id.calendarTVType);
        mCalendarType.setBackgroundColor(Color.WHITE);
        mCalendarType.setText(sch_type[0]+"\t\t\t\t"+remind[remindID]);

        mCalendarEdit = (EditText)findViewById(R.id.calendarET);
        mCalendarEdit.setBackgroundColor(Color.WHITE);
        if(schText != null){
            mCalendarEdit.setText(schText);
            schText = " ";
        }

        Date date = new Date();
        if(hour == -1 && minture == -1){
            hour = date.getHours();
            minture=date.getMinutes();
        }
        mCalendarDate.setText(getCalendarDate());

        //获得日程类型
        mCalendarType.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                schText = mCalendarEdit.getText().toString();
                Intent  intent = new Intent();
                intent.setClass(CalendarViewActivity.this, CalendarTypeActivity.class);
                intent.putExtra("sch_remind", new int[]{sch_typeId, remindID});
                startActivity(intent);
            }
        });
        //获得时间
        mCalendarDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new TimePickerDialog(CalendarViewActivity.this, new TimePickerDialog.OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay, int min) {
                        hour = hourOfDay;
                        minture = min;
                        mCalendarDate.setText(getCalendarDate());
                    }
                }, hour, minture, true).show();
            }
        });
        //保存日程信息
            mCalendarSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                   schText = mCalendarEdit.getText().toString();
                   if(schText.length() == 0){
                       Toast.makeText(CalendarViewActivity.this, "日程信息不能为空", Toast.LENGTH_SHORT).show();
                       return;
                   }else {
                      //将日程信息保存
                      String showDate = handleInfo(Integer.parseInt(calendarYear), Integer.parseInt(tempMonth), Integer.parseInt(tempDay),
                                            hour,minture,week,remindID);
                      CalendarVO  calendarVO = new CalendarVO();
                      calendarVO.setScheduleTypeID(sch_typeId);
                      calendarVO.setRemindID(remindID);
                      calendarVO.setScheduleDate(showDate);
                      calendarVO.setScheduleContent(mCalendarEdit.getText().toString());
                      int scheduleID = Dao.save(calendarVO);
                      String[] scheduleIDs = new String[]{String.valueOf(scheduleID)};
                      Intent intent = new Intent();
                      intent.setClass(CalendarViewActivity.this, CalendarInfoViewActivity.class);
                      intent.putExtra("calendarID", scheduleIDs);
                       startActivity(intent);
                      //设置日程标记日期(将所有日程标记日期封装到list中)
                      setScheduleDateTag(remindID, calendarYear, tempMonth, tempDay, scheduleID);
                  }
            }
        });
    }

    /**
     * 设置日程标记日期
     * @param remindID
     * @param year
     * @param month
     * @param day
     */
    private void setScheduleDateTag(int remindID, String year, String month, String day, int scheduleID) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-M-d");
        String d = year + "-" + month + "-" + day;
        Calendar cal = Calendar.getInstance();
        try {
            cal.setTime(format.parse(d));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //封装要标记的日期
        if(remindID >= 0 && remindID <= 3){
            //"提醒一次","隔10分钟","隔30分钟","隔一小时"（只需标记当前这一天）
            CalendarTag calendarTag = new CalendarTag();
            calendarTag.setYear(Integer.parseInt(year));
            calendarTag.setMonth(Integer.parseInt(month));
            calendarTag.setDay(Integer.parseInt(day));
            calendarTag.setScheduleID(scheduleID);
            dateTagList.add(calendarTag);
        }else if(remindID == 4){
            //每天重复(从设置的日程的开始的之后每一天多要标记)
            for (int i = 0 ; i <= (2049-Integer.parseInt(year))*12*4*7; i++){
                if(i == 0){
                    cal.add(Calendar.DATE, 0);
                }else{
                    cal.add(Calendar.DATE, 1);
                }
                handleDate(cal, scheduleID);
            }
        }else if(remindID == 5){
            //每周重复(从设置日程的这天(星期几)，接下来的每周的这一天多要标记)
            for (int i = 0 ; i <= (2049-Integer.parseInt(year))*12*4; i++) {
                if (i == 0) {
                    cal.add(Calendar.WEEK_OF_MONTH, 0);
                } else {
                    cal.add(Calendar.WEEK_OF_MONTH, 1);
                }
                handleDate(cal, scheduleID);
            }
        }else if(remindID == 6){
            //每月重复(从设置日程的这天(几月几号)，接下来的每月的这一天多要标记)
            for (int i = 0 ; i <= (2049-Integer.parseInt(year))*12; i++) {
                if (i == 0) {
                    cal.add(Calendar.MONTH, 0);
                } else {
                    cal.add(Calendar.MONTH, 1);
                }
                handleDate(cal, scheduleID);
            }
        }else if(remindID == 7){
            //每年重复(从设置日程的这天(哪一年几月几号)，接下来的每年的这一天多要标记)
            for(int i =0; i <= 2049-Integer.parseInt(year); i++){
                if( i== 0 ){
                    cal.add(Calendar.YEAR, 0);
                }else{
                    cal.add(Calendar.YEAR, 1);
                }
                handleDate(cal,scheduleID);
            }
        }
        //将标记日期存入数据库中
        Dao.saveTagDate(dateTagList);
    }

    /**
     * 日程标记日期的处理
     * @param cal
     */
    private void handleDate(Calendar cal, int scheduleID) {
        CalendarTag calendarTag = new CalendarTag();
        calendarTag.setYear(cal.get(Calendar.YEAR));
        calendarTag.setMonth(cal.get(Calendar.MONTH)+1);
        calendarTag.setDay(cal.get(Calendar.DATE));
        calendarTag.setScheduleID(scheduleID);
        dateTagList.add(calendarTag);
    }

    /**
     * 通过选择提醒次数来处理最后的显示结果
     * @param year
     * @param month
     * @param day
     * @param hour
     * @param minute
     * @param week
     * @param remindID
     */
    private String handleInfo(int year, int month, int day, int hour, int minute, String week, int remindID) {
        String remindType = remind[remindID];
        String show = " ";
        if(0 <= remindID && remindID <= 4){
            //提醒一次,隔10分钟,隔30分钟,隔一小时
            show = year + "-" + month + "-" + day + "\t" + hour + ":" + minute + "\t" + week + "\t\t" + remindType;
        }else if(remindID == 5){
            show = "每周" + week + "\t" + hour + ":" + minute;
        }else if(remindID == 6){
            show = "每月" + day + "号" + "\t" + hour + ":" + minute;
        }else if(remindID == 7){
            show = "每年"+ month + "-" + day + "\t" + hour + ":" + minute;
        }
        return show;
    }

    /**
     * 点击item之后，显示的日期信息
     *
     * @return
     */
    private String getCalendarDate() {
        Intent intent = getIntent();
        if(intent.getStringArrayListExtra("scheduleDate") != null){
            CalendarDate = intent.getStringArrayListExtra("scheduleDate");
        }
        int[] Calendar_remind = intent.getIntArrayExtra("schType_remind");
        if(Calendar_remind != null){
            sch_typeId = Calendar_remind[0];
            remindID = Calendar_remind[1];
            mCalendarType.setText(sch_type[sch_typeId]+"\t\t\t\t"+remind[remindID]);
        }
        // 得到年月日和星期
        calendarYear = CalendarDate.get(0);
        calendarMonth = CalendarDate.get(1);
        tempMonth = calendarMonth;
        if(Integer.parseInt(calendarMonth) < 10){
            calendarMonth = "0" + calendarMonth;
        }
        calendarDay = CalendarDate.get(2);
        tempDay = calendarDay;
        if(Integer.parseInt(calendarDay) < 10){
            calendarDay = "0" + calendarDay;
        }

        week = CalendarDate.get(3);
        String hour_c = String.valueOf(hour);
        String minute_c = String.valueOf(minture);
        if(hour  < 10){
            hour_c = "0" + hour_c;
        }
        if(minture < 10){
            minute_c = "0" + minute_c;
        }
        // 得到对应的阴历日期
        String calendarLunarDay = getLunarDay(Integer.parseInt(calendarYear), Integer.parseInt(calendarMonth), Integer.parseInt(calendarDay));
        String calendarLunarMonth = lc.getLunarMonth();
        StringBuffer buffer = new StringBuffer();
        buffer.append(calendarYear).append("-").append(calendarMonth)
                .append("-").append(calendarDay).append(" ").append(hour_c).append(":")
                .append(minute_c).append("\n").append(
                calendarLunarMonth).append(calendarLunarDay)
                .append(" ").append(week);

        return buffer.toString();
    }

    /**
     * 根据日期的年月日返回阴历日期
     *
     * @param year
     * @param month
     * @param day
     * @return
     */
    private String getLunarDay(int year, int month, int day) {
        String lunarDay = lc.getLunarDate(year, month, day, true);
        if(lunarDay.substring(1, 2).equals("月")){
            lunarDay = "初一";
        }
        return lunarDay;
    }
}
